package test.web.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author piaoransheng
 * @Date 2021/10/27 11:18
 */
@RestController
@RequestMapping("/qrCode")
public class QRCodeController {

    @GetMapping("/create")
    public void test1(@RequestParam("linkUrl") String linkUrl, HttpServletResponse response) throws Exception {
        System.out.println("二维码生成");
        //二维码携带信息
        Map<EncodeHintType, Object> map = new HashMap<>();
        //二维码纠错程度 google.zxing
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //字符编码
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //边距
        map.put(EncodeHintType.MARGIN, 1);
        //1.构建二维码对象
        BitMatrix bitMatrix = new MultiFormatWriter().encode(linkUrl, BarcodeFormat.QR_CODE, 300, 300, map);

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        //2.将二维码对象写到BufferedImage对象中
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0XFF000000 : 0xFFFFFFFF);
            }
        }

        //3.将BufferedImage写到response对象
        response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别
        OutputStream os = response.getOutputStream(); //获取文件输出流
        ImageIO.write(bufferedImage, "png", os);//输出图片流
        os.flush();
        os.close();//关闭流
    }
}